package com.example.zhihu.service.Imp;

import com.example.zhihu.mapper.QuestionCustomMapper;
import com.example.zhihu.mapper.QuestionMapper;
import com.example.zhihu.pojo.Question;
import com.example.zhihu.pojo.vo.QuestionVO;
import com.example.zhihu.service.QuestionService;
import com.example.zhihu.utils.PagedResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class QuestionImp implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionCustomMapper questionCustomMapper;

    @Autowired
    private Sid sid;

    @Override
    public Question saveQuestion(Question question) {
        question.setState(1);
        question.setId(sid.nextShort());
        question.setCreateTime(new Date());
        questionMapper.insert(question);
        return question;
    }

    @Override
    public PagedResult questionList(String name, String userId, Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<QuestionVO> qlist = questionCustomMapper.queryQuestion(name, userId);
        PageInfo<QuestionVO> pageList = new PageInfo<>(qlist);
        PagedResult pagedResult = new PagedResult();
        pagedResult.setTotal(pageList.getPages());
        pagedResult.setRows(qlist);
        pagedResult.setRecords(pageList.getTotal());
        pagedResult.setPage(page);
        return pagedResult;
    }

    @Override
    public void delQuestion(String qid) {
        Question question = new Question();
        question.setId(qid);
        question.setState(0);
        questionMapper.updateByPrimaryKeySelective(question);
    }

    @Override
    public void updateQuestion(Question question) {
        Example example = new Example(Question.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(question.getId());
        questionMapper.updateByExampleSelective(question,example);
    }

}
